//
//  CollectionMainViewController.m
//  SmileRead
//
//  Created by dllo on 15/8/27.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "CollectionMainViewController.h"
#import "Path.h"
#import "DB.h"
#import "DBDataBase.h"
#import "ReadDB.h"
#import "ReadDBDataBase.h"
#import "ReadModel.h"
#import "VoiceMusicModel.h"
#import "ReadCell.h"
#import "VoiceMusicCell.h"
#import "VoiceDetailViewController.h"
#import "ReadSecondViewController.h"
#import "FileNameList.h"


@interface CollectionMainViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIImageView *backImage;
@property (nonatomic, retain) UIVisualEffectView *effectView;
@property (nonatomic, retain) UILabel *logleLabel;
@property (nonatomic, retain) UIImageView *personImage;
@property (nonatomic, retain) NSMutableArray *arrayOfRead;
@property (nonatomic, retain) NSMutableArray *arrayOfMusic;

@end

@implementation CollectionMainViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrayOfMusic = [NSMutableArray array];
        self.arrayOfRead = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc
{
    [_personImage release];
    [_logleLabel release];
    [_effectView release];
    [_backImage release];
    [_tableView release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.arrayOfRead removeAllObjects];
    [self.arrayOfMusic removeAllObjects];
    self.logleLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"name"];
    [self handelData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createSubView];
    //[self handelData];
}

- (void)handelData
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSArray *array = [ReadDBDataBase selectAll].mutableCopy;
        
        NSArray *array1= [DBDataBase selectAll].mutableCopy;
        
        // 回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            // 回到主线程
            [self.arrayOfMusic addObjectsFromArray:array1];
            [self.arrayOfRead addObjectsFromArray:array];
            [self.tableView reloadData];
        });
    });
}

- (void)createSubView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    [self createHeaderView];
    [_tableView release];
}

- (void)createHeaderView
{
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250 * heightFit)] autorelease];
    self.backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250 *heightFit)];
    [headerView addSubview:self.backImage];
    self.backImage.image = [UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"7.jpg"]];
    self.backImage.userInteractionEnabled = YES;
    
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.effectView = [[UIVisualEffectView alloc] initWithEffect:blur];
    self.effectView.frame = CGRectMake(0, 0, self.view.frame.size.width, 250 * heightFit);
    [self.backImage addSubview:self.effectView];
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(15 * widthFit, 25 * heightFit, 40 * widthFit, 40 * widthFit)];
    [backButton setBackgroundImage:[UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"back.png"]] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    backButton.layer.cornerRadius = backButton.frame.size.width / 2;
    backButton.layer.masksToBounds = YES;
    [self.effectView.contentView addSubview:backButton];
    
    self.logleLabel = [[UILabel alloc] initWithFrame:CGRectMake(40 * widthFit, 150 * heightFit, self.effectView.frame.size.width - 80 * widthFit, 80 * heightFit)];
    self.logleLabel.numberOfLines = 0;
    self.logleLabel.font = [UIFont systemFontOfSize:23];
    self.logleLabel.textAlignment = NSTextAlignmentCenter;
    
    self.personImage = [[UIImageView alloc] initWithFrame:CGRectMake(headerView.frame.size.width / 2 - 40 * widthFit, 65 * heightFit, 80 * heightFit, 80 * heightFit)];
    self.personImage.layer.cornerRadius = self.personImage.frame.size.width / 2;
    self.personImage.layer.masksToBounds = YES;
    
    [self.effectView.contentView addSubview:self.personImage];
    [self.effectView.contentView addSubview:self.logleLabel];
    
#warning 设置个性化
    
    NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [userInfo objectForKey:LY_PERSON];
    
    if (dic == nil) {
        self.logleLabel.textAlignment = NSTextAlignmentCenter;
        NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"Our mind is a sponge, Our heart is a stream" attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
        self.logleLabel.attributedText = string;
        self.personImage.image = [UIImage imageWithContentsOfFile:[Path pathOfImageWithName:@"9.jpg"]];
    }
    else {
        if ([dic objectForKey:@"name"] != nil) {
            
            NSAttributedString *string = [[NSAttributedString alloc] initWithString:[dic objectForKey:@"name"] attributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
            self.logleLabel.attributedText = string;
        }
        NSString *str = [Path pathOfLibraryWithFileName:LY_Image];
        self.personImage.image = [UIImage imageWithContentsOfFile:str];
    }
    
    self.tableView.tableHeaderView = headerView;
    [_personImage release];
    [_logleLabel release];
    [backButton release];
}

- (void)backClick:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.arrayOfMusic.count;
        
    }
    else {
        return self.arrayOfRead.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 100 * heightFit;
    }
    else {
        return 150 * heightFit;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identOfMusic = @"music";
    static NSString *identOfRead = @"read";
    VoiceMusicCell *cellOfMusic = [tableView dequeueReusableCellWithIdentifier:identOfMusic];
    ReadCell *cellOfRead = [tableView dequeueReusableCellWithIdentifier:identOfRead];
    
    if (indexPath.section == 0) {
        if (cellOfMusic == nil) {
            cellOfMusic = [[[VoiceMusicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identOfMusic] autorelease];
        }
        cellOfMusic.model = self.arrayOfMusic[indexPath.row];
        cellOfMusic.selectionStyle = UITableViewCellSelectionStyleNone;
        return cellOfMusic;
    }
    else {
        
        if (cellOfRead == nil) {
            cellOfRead = [[[ReadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identOfRead] autorelease];
        }
        cellOfRead.model = self.arrayOfRead[indexPath.row];
        cellOfRead.selectionStyle = UITableViewCellSelectionStyleNone;
        return cellOfRead;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        VoiceDetailViewController *detail = [[VoiceDetailViewController alloc] init];
        [detail receiveWithModel:self.arrayOfMusic[indexPath.row]];
        [self presentViewController:detail animated:YES completion:^{
            
        }];
        [detail release];
    }
    else {
        
        ReadSecondViewController *read = [[ReadSecondViewController alloc] init];
        [read receivewithModel:self.arrayOfRead[indexPath.row]];
        [self presentViewController:read animated:YES completion:^{
            
        }];
        [read release];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"你喜欢的电台";
    }
    else {
        return @"你喜欢的文章";
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
